package com.health.viewscontrols.medical.device.bp;

import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.health.httpbean.model.BpModel;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.views.BlueToothConstant;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

/**
 * 辰浩血压计4.0
 */
public class FSRKBb4Activity extends BaseDeviceActivity {

    public UUID DEVICE_SERVICE_UUID_FSRKB = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");
    public UUID DEVICE_NOTIFY_UUID_FSRKB = UUID.fromString("0000fff6-0000-1000-8000-00805f9b34fb");
    public UUID DEVICE_WRITE_UUID_FSRKB = UUID.fromString("0000fff6-0000-1000-8000-00805f9b34fb");

    Timer timer;
    TimerTask task;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            connDevice();
        }
    };

    private BleDevice fastBleDevice;

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bp_chenhao);
//        mBleDevice.setDevice_Service_UUID(DEVICE_SERVICE_UUID_FSRKB);
//        mBleDevice.setDevice_Notify_UUID(DEVICE_NOTIFY_UUID_FSRKB);
//        mBleDevice.setDEVICE_write_UUID(DEVICE_WRITE_UUID_FSRKB);
//        mBleDevice.setConnectChangedListener(new OnDeviceConnectChangedListener() {
//            @Override
//            public void onConnected() {
//                Log.e(TAG, "onConnected: ");
//                isConnected = true;
//                runOnUiThread(() -> {
//                    if (timer != null) {
//                        timer.cancel();
//                    }
//                    blueToothState.setText("蓝牙已连接");
//                    showProgressDialog("等待接收血压计数据");
//                    new Handler().postDelayed(() -> write(BlueToothConstant.CONN_DEVICE_COMMAND), 1200);
//                });
//            }
//
//            @Override
//            public void onDisconnected() {
//                isConnected = false;
//                Log.e(TAG, "onDisconnected: ");
//                cancelProgressDialog();
//                runOnUiThread(() -> {
//                    blueToothState.setText("蓝牙连接失败");
//                });
//            }
//        });
//
//        startDevice();

        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 5000)
                .setConnectOverTime(10000)
                .setOperateTimeout(5000);

        startDevice();
    }

    private void connDevice() {
        if (isConnected) {
            blueToothState.setText("蓝牙已连接");
            showProgressDialog("等待接收血压计数据");
            new Handler().postDelayed(() -> write(BlueToothConstant.CONN_DEVICE_COMMAND), 1200);
        } else {
            showProgressDialog("正在连接设备");
            blueToothState.setText("蓝牙开始连接");
            Log.e(TAG, "startDevice: " + deviceEnum.getMac());
            mBleDevice.setConnect(true);
            mBleDevice.setMAC(deviceEnum.getMac());
            mBleDevice.connect(deviceEnum.getMac());
        }
    }

    @Override
    public void startDevice() {
//        connDevice();
//        timer = new Timer();
//        task = new TimerTask() {
//            @Override
//            public void run() {
//                Message msg = new Message();
//                msg.what = 0;
//                handler.sendMessage(msg);
//            }
//        };
//        timer.schedule(task,6000);

        if (fastBleDevice == null) {
            showProgressDialog("正在连接" + deviceEnum.getTitle());
//            connectionPwBle();
            BleManager.getInstance().scan(new BleScanCallback() {
                @Override
                public void onScanStarted(boolean success) {
                }

                @Override
                public void onLeScan(BleDevice bleDevice) {
                    super.onLeScan(bleDevice);
                }

                @Override
                public void onScanning(BleDevice bleDevice) {
                    if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                        connectionPwBle();
                    }
                }

                @Override
                public void onScanFinished(List<BleDevice> scanResultList) {

                }
            });
        } else {
            ToastUtils.showShort("设备已连接，请等待测量结果");
            showProgressDialog("等待接收血压数据");
        }
    }

    private void connectionPwBle() {
        BleManager.getInstance().connect(deviceEnum.getMac(), new BleGattCallback() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("蓝牙开始连接");
                showProgressDialog("正在连接血压设备");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG, "onConnectFail: " +  exception.toString());
                blueToothState.setText("蓝牙连接失败");
                connectionPwBle();
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                Log.e(TAG, "onConnectSuccess: " + bleDevice.getMac() );
                blueToothState.setText("蓝牙已连接");
                fastBleDevice = bleDevice;
                showProgressDialog("等待接收血压数据");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPwNotify(bleDevice);
                    }
                },500);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                blueToothState.setText("蓝牙已断开连接");
                disconnectDevice();
                cancelProgressDialog();
            }
        });
    }

    private void getPwNotify(final BleDevice bleDevice) {
        BleManager.getInstance().notify(bleDevice,
                DEVICE_SERVICE_UUID_FSRKB.toString(),
                DEVICE_NOTIFY_UUID_FSRKB.toString(),
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: " );
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " +exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        //接收数据
                        String hexString = HexUtil.formatHexString(data);
                        Log.e(TAG, "onCharacteristicChanged: "+ hexString );
//                        int bloodUp = Integer.parseInt(hexString.substring(4, 6) + hexString.substring(2, 4), 16);
//                        tv_result.setText("实时数据: " + bloodUp + " /mmHg");

                        resolveData(hexString);
                    }
                });
    }

    private void resolveData(String hexString) {
        try {
            String type = hexString.substring(0, 4);
            if (hexString.length() >=28) {
                if ("D0C2".equalsIgnoreCase(type)) {
                    int bloodUp = Integer.parseInt(hexString.substring(8, 10), 16);
                    int bloodDown = Integer.parseInt(hexString.substring(10, 12), 16);
                    int heart = Integer.parseInt(hexString.substring(12, 14), 16);
                    Log.e(TAG, "高压: " + bloodUp + "  低压：" + bloodDown + "  心率：" + heart);
                    saveMaiboboData(bloodUp, bloodDown, heart);
                }
            } else if (hexString.length() == 16) {
                if ("D0C2".equalsIgnoreCase(type)) {
                    int bloodDown = Integer.parseInt(hexString.substring(10, 12), 16);
                    tv_result.setText("实时血压：\n        " + bloodDown);
                    Log.e(TAG, "实时血压: " + bloodDown);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(String hexString) {
        try {
            String type = hexString.substring(0, 4);
            if (hexString.length() >=28) {
                if ("D0C2".equalsIgnoreCase(type)) {
                    int bloodUp = Integer.parseInt(hexString.substring(8, 10), 16);
                    int bloodDown = Integer.parseInt(hexString.substring(10, 12), 16);
                    int heart = Integer.parseInt(hexString.substring(12, 14), 16);
                    Log.e(TAG, "高压: " + bloodUp + "  低压：" + bloodDown + "  心率：" + heart);
                    saveMaiboboData(bloodUp, bloodDown, heart);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveMaiboboData(int bloodUp, int bloodDown, int heart) {
        try {
//            disconnectDevice();
            cancelProgressDialog();
            //收缩压、舒张压、心率
            String results = DeviceShowSaveData.getDataShow(bloodUp + ";" + bloodDown + ";" + heart + ";",
                    BluetoothConstant.XUEYA_YE680A_YUYUE);

            BpModel bpModel = new BpModel();
            bpModel.setHighpressure(bloodUp + "");
            bpModel.setLowvoltage(bloodDown + "");
            bpModel.setPulse(heart + "");
            DeviceShowSaveData.saveChenhaoBp(GsonUtils.toJson(bpModel));

            tv_result.setText("测量结果：\n        " + results);
            tv_state.setText("获取测量结果成功");

            cancelProgressDialog();
        } catch (Exception e) {
            Log.e(TAG, "报异常了: " + e.toString());
        }
    }

    @Override
    public void disconnectDevice() {
        try {
            cancelProgressDialog();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.e(TAG, "disconnectDevice: " );
        try {
            cancelProgressDialog();
            fastBleDevice = null;
            BleManager.getInstance().disconnectAllDevice();
            BleManager.getInstance().destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

}
